package com.weipai.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.weipai.demo.enums.RetCode;
import com.weipai.demo.mapper.CreditSettingMapper;
import com.weipai.demo.model.CreditSetting;
import com.weipai.demo.service.CreditSettingService;
import com.weipai.demo.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CreditSettingServiceImpl implements CreditSettingService {

    @Autowired
    private CreditSettingMapper creditSettingMapper;

    @Override
    public Response getAll() {
        Response response = new Response();
        List<CreditSetting> res = creditSettingMapper.selectAll();
        response.setCode(RetCode.SUCCESS);
        response.setData(res);
        return response;
    }

    @Override
    public Response setSetting(String  creditSetting) {
        Response response = new Response();
        try {
            Integer res = 0;
            List<Map<String,Object>> jsonArray = (List<Map<String,Object>>) JSONObject.parse(creditSetting);
            for (Map<String,Object> item: jsonArray
                 ) {
                CreditSetting creditSetting1 = new CreditSetting();
                creditSetting1.setId((Integer) item.get("id"));
                creditSetting1.setName((String) item.get("name"));
                creditSetting1.setValue((String) item.get("value"));
                res = creditSettingMapper.updateByPrimaryKeySelective(creditSetting1);
            }
//            if (creditSetting.getId() > 0) { //添加属性
//                res = creditSettingMapper.updateByPrimaryKeySelective(creditSetting);
//            } else {
//                res = creditSettingMapper.insert(creditSetting);
//            }
            if (res > 0) {
                response.setCode(RetCode.SUCCESS);
            }else{
                response.setCode(RetCode.REQUEST_ERROR);
            }

        } catch (Exception e) {
            response.setCode(RetCode.REQUEST_ERROR);
            response.setData(e.getMessage());
        }

        return response;
    }
}
